﻿using Abp.AutoMapper;
using Abp.Modules;
using Abp.Reflection.Extensions;
using FwProject.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using System;
using Abp.RemoteEventBus.Redis;
using Abp.RemoteEventBus;
using Abp.RemoteEventBus.RabbitMQ;
using FwProject.PublicService.SqlExec;
using System.Collections.Generic;
using System.Reflection;
using Abp.EntityFrameworkCore;
using Castle.MicroKernel.Registration;
using Abp.Runtime.Caching.Redis;
using FwProject.CatchUntil;
using Castle.Windsor;
using Abp.Dependency;
using Abp.Configuration.Startup;
using FwProject.Comm;
using Abp.Threading.BackgroundWorkers;
using FwProject.BackGround.DistributionEnter;
using FwProject.BackGround.Settlement;
using Castle.MicroKernel;
using Abp.Application.Services;
using Castle.Core;
using FwProject.Core.DataFilterFactoryinfo;
using FwProject.DataFilterFactoryinfo;

namespace FwProject
{
       [DependsOn(
        typeof(FwProjectCoreModule),
        typeof(AbpAutoMapperModule),
        typeof(AbpRemoteEventBusRabbitMQModule),
        typeof(AbpRemoteEventBusRedisModule),
        typeof(AbpEntityFrameworkCoreModule),
        typeof(AbpRedisCacheModule),
        typeof(FwProjectPublicServiceModule))]
    public class FwProjectApplicationModule : AbpModule
    {


        private readonly IHostingEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;

        public FwProjectApplicationModule(IHostingEnvironment env)
        {
            _env = env;
            _appConfiguration = env.GetAppConfiguration();
        }

        public override void PreInitialize()
        {
           
          
            Configuration.Authorization.Providers.Add<FwProjectAuthorizationProvider>();
            /// <param>缓存配置</param>
            Configuration.Caching.ConfigureAll(cache =>
            {
                cache.DefaultSlidingExpireTime = TimeSpan.FromHours(2);
            });
            Configuration.Caching.AbpConfiguration.ReplaceService<IRedisCacheSerializer, RedisCatch>(DependencyLifeStyle.Transient);
            Configuration.UnitOfWork.RegisterFilter(FwConsts.FactroyInfoFilter, true);
            //Configuration.IocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered;
            InterceptorRegistrarFactory.Initialize(IocManager.IocContainer.Kernel);
            //Configuration.Caching.UseRedis(options =>
            //{
            //    Logger.Info(_appConfiguration["Abp:RedisCache:ConnectionString"]);
            //    options.ConnectionString = _appConfiguration["Abp:RedisCache:ConnectionString"];
            //    options.DatabaseId = _appConfiguration.GetValue<int>("Abp:RedisCache:DatabaseId");
            //    Logger.Info("缓存开启");
            //});

        }
        //服务过滤工厂信息
        private static void Kernel_ComponentRegistered(string key, IHandler handler)
        {
            //if (typeof(IApplicationService).IsAssignableFrom(handler.ComponentModel.Implementation))
            //{
            //    handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(FilterFactoryinfoInterceptor)));
            //}
        }

        public override void PostInitialize()
        {
          
            try
            {

                //Configuration.Modules.RemoteEventBus().UseRedis().Configure((setting) =>
                //{
                //    Logger.Info("采用redis 替代消息队列");
                //    setting.Server = _appConfiguration["JPushmessage:JPushmessageModel:Exception"];
                //});


                Configuration.Modules.RemoteEventBus().UseRabbitMQ().Configure(setting =>
                {
                    // setting.Url = _appConfiguration["JPushmessage:JPushmessageModel:localServer"];
#if DEBUG
                    setting.Url = _appConfiguration["JPushmessage:JPushmessageModel:localServer"];
#else
                    setting.Url = _appConfiguration["JPushmessage:JPushmessageModel:Server"];
#endif
                    // "amqp://guest:guest@127.0.0.1:5672/";
                });


            }
            catch (Exception exe)
            {
                         Logger.Error("mq 失败采用redis 替代",exe);
                         Configuration.Modules.RemoteEventBus().UseRedis().Configure((setting) =>
                          {
                            setting.Server = _appConfiguration["JPushmessage:JPushmessageModel:Exception"];  
                        });
            }

            // enable auto subscribe
            // will scan class which use RemoteEventHandlerAttribute and auto subscribe topic base the attribute info

            Configuration.Modules.RemoteEventBus().AutoSubscribe();
        }

        public override void Initialize()
        {
            var thisAssembly = typeof(FwProjectApplicationModule).GetAssembly();

            IocManager.RegisterAssemblyByConvention(thisAssembly);
           
            Configuration.Modules.AbpAutoMapper().Configurators.Add(
                // Scan the assembly for classes which inherit from AutoMapper.Profile
                cfg => cfg.AddProfiles(thisAssembly)
            );
        }
        /// <summary>
        /// 激光推送配送
        /// </summary>
       
    }
}
